package com.example.cardgame

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import cn.edu.sicnu.cardgame.Card
import cn.edu.sicnu.cardgame.CardMatchingGame

class FirstActivity : AppCompatActivity() , View.OnClickListener{
    lateinit var  game: CardMatchingGame
    val cardButtons= mutableListOf<Button>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_first)
        val gridLayout=findViewById<androidx.gridlayout.widget.GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children){
            if(v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()
        val reset=findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            val intent = Intent()
            intent.putExtra("score", game.score)
            setResult(Activity.RESULT_OK, intent)
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

    }
    fun updateUI() {
        for (button in cardButtons) {
            val card = game.cardAtIndex(cardButtons.indexOf(button))
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.cardback)
            }
        }

        val score=findViewById<TextView>(R.id.score)
        score.text=String.format("%s%d","分数: ",game.score)
    }


    override fun onClick(v: View?){
        if(v is Button){
            val index= cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        val intent = Intent()
        intent.putExtra("score", game.score)
        setResult(Activity.RESULT_OK, intent)
    }
}